package org.mikrosopht.client;

import com.google.gwt.user.client.ui.Composite;

public class MovieListPagerController extends Composite implements MovieListPagerEventReceiver {

  private Runnable runOnUpdate;
  private MovieListPager moviePager;
  public int offset;
  public int maxOffset = -1;
  public boolean showAll;

  public MovieListPagerController(Runnable runOnUpdate) {
    this.runOnUpdate = runOnUpdate;
    this.moviePager = new MovieListPager(this);
    offset = 0;
    showAll = false;
    moviePager.setDisabled(MovieListPager.Button.FIRST);
    moviePager.setDisabled(MovieListPager.Button.PREVIOUS);
    initWidget(moviePager);
  }

  public void setMaxOffset(int max) {
    maxOffset = max;
  }

  public void resetOffset() {
    offset = 0;
  }

  public void onClick(MovieListPager.Button button) {
    moviePager.setDisabled(button);
    switch (button) {
      case FIRST:
        offset = 0;
        moviePager.setDisabled(MovieListPager.Button.PREVIOUS);
        break;
      case NEXT:
        offset++;
        break;
      case PREVIOUS:
        offset--;
        break;
      case LAST:
        if (maxOffset >= 0) {
          offset = maxOffset;
        }
        break;
      case ALL:
        if (showAll) {
          moviePager.setEnabled(button);
        }
        showAll = showAll ? false : true;
        updateButtons();
        break;
    }
    if (offset < 0 || (maxOffset >= 0 && offset > maxOffset)) {
      offset = 0;
    }
    runOnUpdate.run();
  }

  public void updateButtons() {
    if (offset > 0) {
      moviePager.setEnabled(MovieListPager.Button.FIRST);
      moviePager.setEnabled(MovieListPager.Button.PREVIOUS);
      moviePager.setEnabled(MovieListPager.Button.NEXT);
      moviePager.setEnabled(MovieListPager.Button.LAST);
    } else {
      moviePager.setDisabled(MovieListPager.Button.FIRST);
      moviePager.setDisabled(MovieListPager.Button.PREVIOUS);
      moviePager.setEnabled(MovieListPager.Button.NEXT);
      moviePager.setEnabled(MovieListPager.Button.LAST);
    }
    if (showAll) {
      moviePager.setDisabled(MovieListPager.Button.ALL);
      moviePager.setDisabled(MovieListPager.Button.FIRST);
      moviePager.setDisabled(MovieListPager.Button.PREVIOUS);
      moviePager.setDisabled(MovieListPager.Button.NEXT);
      moviePager.setDisabled(MovieListPager.Button.LAST);
    } else {
      moviePager.setEnabled(MovieListPager.Button.ALL);
    }
    if (offset == maxOffset) {
      moviePager.setDisabled(MovieListPager.Button.NEXT);
      moviePager.setDisabled(MovieListPager.Button.LAST);
    }
  }

}
